package com.haolijun.eecms.controller;

import cn.hutool.core.lang.UUID;
import com.haolijun.eecms.common.R;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @ClassName FilesUploadController
 * @Description TODO
 * @Author hljstart
 * @Date 2023/3/11 10:54
 * @Version 1.0
 */
@RestController
@RequestMapping("/upload")
@Tag(name = "FilesUploadController",description = "文件上传接口")
public class FilesUploadController {

    private final String URL = "http://eecms.natapp1.cc/eecms/image/";

    @PostMapping("/fileUpload")
    public R upload(@RequestPart("photo") MultipartFile photo) throws IOException {
        // 1、随机名字
        String uuid = UUID.randomUUID().toString(true).toUpperCase();

        if(!photo.isEmpty()){
            // 2、获取文件的名字
            String fileName = photo.getOriginalFilename();
            // 3、设置新的名称
            int index = fileName.lastIndexOf(".");
            String suffix = fileName.substring(index);
            fileName = uuid + suffix;
            // 保存到服务器
            photo.transferTo(new File("D:\\file_image\\" + fileName));
            return R.ok().data("photo", URL + fileName);
        }
        return R.error();
    }
}
